package com.hjzd.ai.smartpractice.service.impl;

import com.hjzd.ai.smartpractice.service.RedisService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author pengyonglei
 * @version 1.0.0
 */
@Service
public class RedisServiceImpl implements RedisService {

	private static final Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);

	@Resource
	private RedisTemplate<String, String> redisTemplate;

	@PostConstruct
	private void init() {
		// 设置序列器, 以防止使用默认的 JdkSerializationRedisSerializer 导致乱码
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new StringRedisSerializer());
	}

	@Override
	public String get(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	@Override
	public boolean set(String key, String value, int expire) {
		try {
			if (expire == -1) {
				// -1 表示不设置到期时间, 常规缓存不建议使用
				redisTemplate.opsForValue().set(key, value);
			} else {
				redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
			}
		} catch (Exception ex) {
			logger.error(">>> redis set error. ex=", ex);
			return false;
		}
		return true;
	}

	@Override
	public boolean set(String key, String value, long timeout, TimeUnit timeUnit) {
		try {
			redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
		} catch (Exception ex) {
			logger.error(">>> redis set error. ex=", ex);
			return false;
		}
		return true;
	}

	@Override
	public boolean remove(String key) {
		try {
			redisTemplate.delete(key);
		} catch (Exception ex) {
			logger.error(">>> redis remove error. ex=", ex);
			return false;
		}
		return true;
	}

	@Override
	public Set<String> keys(String pattern) {
		return redisTemplate.keys(pattern);
	}

	@Override
	public boolean addValueToSet(String key, String value) {
		try {
			redisTemplate.opsForSet().add(key, value);
			redisTemplate.expire(key, 24, TimeUnit.HOURS);
			return true;
		} catch (Exception ex) {
			logger.error(">>> redis addValueToSet error. ex=", ex);
		}
		return false;
	}

	@Override
	public boolean removeValueFromSet(String key, String value) {
		try {
			redisTemplate.opsForSet().remove(key, value);
			return true;
		} catch (Exception ex) {
			logger.error(">>> redis removeValueFromSet error. ex=", ex);
		}
		return false;
	}

	@Override
	public Set<String> getValueSet(String key) {
		try {
			return redisTemplate.opsForSet().members(key);
		} catch (Exception ex) {
			logger.error(">>> redis getValueSet error. ex=", ex);
		}
		return new HashSet<>();
	}


}
